# -*- coding: utf-8 -*-
"""
Created on Mon Aug 14 15:33:17 2017

@author: XFBY
"""

import pandas as pd
import numpy as np
from sklearn.model_selection import ShuffleSplit
from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
import matplotlib as mpl
import seaborn as sns
from sklearn.cross_validation import KFold


def skdata2df(skdata):
    dfdata = pd.DataFrame(skdata.data, columns=skdata.feature_names)
    dfdata["target"] = skdata.target
    return dfdata


# 箱线图
'''
每个特征作为x轴,箱线图包含数据的最大和最小四分位，
箱子中间的黑线代表中指中位数，边缘线代表最大值和最小值（异常点除外），菱形代表异常点
'''


def box_viz(df):
    # mpl.rcParams['font.sans-serif'] = ['SimHei']
    mpl.rcParams['font.sans-serif'] = ['Microsoft YaHei']
    ax = sns.boxplot(df)
    # ax = sns.violinplot(df)
    plt.xticks(rotation=600)
    plt.savefig('box_viz.png', dpi=900)
    plt.show()


# 散点矩阵图
'''
在散点图中把所有特征配对（每两两特征组合画在一个矩阵中）绘制，
对角一般留白或者用来显示核密度估计、直方图或者特征标注。
散点图矩阵可以检查两两不同特征之间的关系。
可从散点图矩阵中找出协方差，线性关系、二次关系或者指数关系，同方差或者异方差（代表特征之间分散的程度）
'''


def covr(df):
    cm = np.corrcoef(df[df.columns].values.T)  # 计算相关系数
    sns.set(font_scale=1.5)

    # 画相关系数矩阵的热点图
    hm = sns.heatmap(cm,
                     annot=True,
                     square=True,
                     fmt='.2f',
                     annot_kws={'size': 15},
                     yticklabels=df.columns,
                     xticklabels=df.columns)
    plt.tight_layout()
    # plt.savefig('./figures/corr_mat.png', dpi=300)


# ==============================================================================
# 协方差矩阵
# ==============================================================================
def splom_viz(df, labels=None):
    mpl.rcParams['font.sans-serif'] = ['Microsoft YaHei']
    ax = sns.pairplot(df, hue=labels, diag_kind='kde', size=3)
    # plt.savefig('splom_viz.png',dpi=900)
    plt.show()


# ==============================================================================
# 均方误作为cost的回归
# ==============================================================================

def get_rmse_of_regression(data, target, cv=10, fit_intercept=True):
    kf = KFold(len(data), n_folds=cv, shuffle=True)
    err_test_all, err_train_all = 0, 0
    for train, test in kf:
        lr = LinearRegression(fit_intercept=fit_intercept)
        lr.fit(data[train], target[train])
        pre_train = lr.predict(data[train])
        err_train = pre_train - target[train]
        err_train_all += np.sum(err_train * err_train)
        pre_test = lr.predict(data[test])
        err_test = pre_test - target[test]
        err_test_all += np.sum(err_test * err_test)
    rmse_test = np.sqrt(err_test_all / len(data))
    rmse_train = np.sqrt(err_train_all / (cv - 1.0) / len(data))
    return rmse_test, rmse_train, pre_test, target[test]


# 定义一个绘图函数用于展示
def lin_regplot(X, y, model):
    plt.scatter(X, y, c='lightblue')
    plt.plot(X, model.predict(X), color='red', linewidth=2)
    return None


if __name__ == '__main__':
    boston = load_boston()

    x = boston.data
    y = boston.target
    df_bs = skdata2df(boston)
    '''
    lr = LinearRegression()
    lr.fit(boston.data, boston.target)
    LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)
    predictions = lr.predict(boston.data)


    f, ax = plt.subplots(figsize=(7, 5))
    f.tight_layout()
    ax.hist(boston.target-predictions,bins=40, label='Residuals Linear', color='b', alpha=.5);
    ax.set_title("Histogram of Residuals")
    ax.legend(loc='best')
    test_r,train_r,pt,tt = get_rmse_of_regression(x, y, cv=10, fit_intercept=True)
    '''
    slr = LinearRegression()
    slr.fit(x, y)
    print(slr)

